package com.lagou.edu.wwy.mvcframework.pojo;

import com.lagou.edu.wwy.mvcframework.annotation.LagouService;
import com.lagou.edu.wwy.mvcframework.annotation.Security;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;

@LagouService
public class SecurityHandlerInterceptor implements HandlerInterceptor {
    private static final String USERNAME = "username";

    @Override
    public boolean preHandler(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Handler han = (Handler) handler;
        Method method = han.getMethod();
        Map<String, String[]> parameterMap = request.getParameterMap();
        Security security = null;
        if (method.isAnnotationPresent(Security.class)) {
            //判断方法上的权限声明
            security = method.getAnnotation(Security.class);

        } else {
            //判断类上的权限声明
            Class<?> aClass = han.getController().getClass();
            if (aClass.isAnnotationPresent(Security.class)) {
                security = aClass.getAnnotation(Security.class);
            }
        }
        if (security != null){
            String[] permission = security.value();
            String[] users = parameterMap.get(USERNAME);
            String username = StringUtils.join(users, ",");
            if (StringUtils.isBlank(username)){
                //如果未传用户名，返回401
                writeFail(response,401,"未登录");
                return false;
            }
            if (permission == null || permission.length == 0) {
                //如果未声明指定账号，则只要上传username即可
                return true;
            } else {
                //如果声明了指定账号可以访问，则需要判断该账号与参数相等
                for (String per : permission) {
                    if (Objects.equals(per,username)){
                        //验证通过
                        return true;
                    }
                }
                writeFail(response,403,"没有权限");
                return false;
            }
        }
        //如果未添加注解，则可以访问
        return true;
    }

    private void writeFail(HttpServletResponse response, int status, String result) {
        try {
            response.setStatus(status);
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
